package com.markedquilt.comment.coomon;

import com.markedquilt.comment.controller.admin.AdminController;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author ZhangKe
 * @Description
 * @date 2020/4/20 12:52.
 */
@Aspect
@Configuration
public class ControllerAspect {

    @Autowired
    HttpServletRequest httpServletRequest;

    @Autowired
    HttpServletResponse httpServletResponse;


    @Around("execution(* com.markedquilt.comment.controller.admin.*.*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public Object adminCtrollerBeforeValidation(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method=((MethodSignature)joinPoint.getSignature()).getMethod();
        AdminPermission adminPermission = method.getAnnotation(AdminPermission.class);
        if (adminPermission==null){
            /** 可放行的公共方法 */
            Object resultObject=joinPoint.proceed();
            return resultObject;
        }
        //判断当前管理员是否登陆
        String email= (String) httpServletRequest.getSession().getAttribute(AdminController.CURRENT_ADMIN_SESSION);
        if (email==null){
            if (adminPermission.produceType().equals("text/html")){
                httpServletResponse.sendRedirect("admin/admin/loginpage");
                return null;
            }else{
                CommonError commonError=new CommonError(EmBussinessError.ADMIN_SHOULD_LOGIN);
                return CommonRes.create(commonError,"fail");
            }

        }else{
            Object resultObject=joinPoint.proceed();
            return resultObject;
        }
    }
}
